"""
数据库模型定义
包含用户表(User)和邮件表(Email)的SQLAlchemy模型
"""
from datetime import datetime
from flask_sqlalchemy import SQLAlchemy
from flask_login import UserMixin
from werkzeug.security import generate_password_hash, check_password_hash
from app import db

class User(UserMixin, db.Model):
    """
    用户模型
    包含用户基本信息、认证信息和权限管理
    """
    __tablename__ = 'users'
    
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(80), unique=True, nullable=False, index=True)
    email = db.Column(db.String(120), unique=True, nullable=False, index=True)
    password_hash = db.Column(db.String(255), nullable=False)
    role = db.Column(db.String(20), nullable=False, default='student')  # student, admin
    real_name = db.Column(db.String(50), nullable=True)  # 真实姓名
    class_id = db.Column(db.Integer, nullable=True, index=True)  # 班级号(0-10)
    is_active = db.Column(db.Boolean, default=True, nullable=False)
    created_at = db.Column(db.DateTime, default=datetime.utcnow, nullable=False)
    last_login = db.Column(db.DateTime)
    
    # 关系定义
    sent_emails = db.relationship('Email', foreign_keys='Email.sender_id', 
                                backref='sender', lazy='dynamic', cascade='all, delete-orphan')
    received_emails = db.relationship('Email', foreign_keys='Email.recipient_id', 
                                    backref='recipient', lazy='dynamic', cascade='all, delete-orphan')
    
    def __init__(self, username, email, role='student', real_name=None, class_id=None):
        """
        初始化用户对象
        
        Args:
            username: 用户名
            email: 邮箱地址
            role: 用户角色，默认为student
            real_name: 真实姓名
            class_id: 班级号(0-10)
        """
        self.username = username
        self.email = email
        self.role = role
        self.real_name = real_name
        self.class_id = class_id
    
    def set_password(self, password):
        """
        设置用户密码（加密存储）
        
        Args:
            password: 明文密码
        """
        self.password_hash = generate_password_hash(password)
    
    def check_password(self, password):
        """
        验证用户密码
        
        Args:
            password: 待验证的明文密码
        
        Returns:
            bool: 密码是否正确
        """
        return check_password_hash(self.password_hash, password)
    
    def is_admin(self):
        """
        检查用户是否为管理员
        
        Returns:
            bool: 是否为管理员
        """
        return self.role == 'admin'
    
    def get_inbox_count(self):
        """
        获取收件箱邮件数量
        
        Returns:
            int: 收件箱邮件数量
        """
        return self.received_emails.filter_by(is_deleted_by_recipient=False).count()
    
    def get_sent_count(self):
        """
        获取发件箱邮件数量
        
        Returns:
            int: 发件箱邮件数量
        """
        return self.sent_emails.filter_by(is_deleted_by_sender=False).count()
    
    def get_unread_count(self):
        """
        获取未读邮件数量
        
        Returns:
            int: 未读邮件数量
        """
        return self.received_emails.filter_by(is_read=False, is_deleted_by_recipient=False).count()
    
    def to_dict(self):
        """
        将用户对象转换为字典
        
        Returns:
            dict: 用户信息字典
        """
        return {
            'id': self.id,
            'username': self.username,
            'email': self.email,
            'role': self.role,
            'real_name': self.real_name,
            'class_id': self.class_id,
            'is_active': self.is_active,
            'created_at': self.created_at.isoformat() if self.created_at else None,
            'last_login': self.last_login.isoformat() if self.last_login else None,
            'inbox_count': self.get_inbox_count(),
            'sent_count': self.get_sent_count(),
            'unread_count': self.get_unread_count()
        }
    
    def __repr__(self):
        return f'<User {self.username}>'

class Email(db.Model):
    """
    邮件模型
    包含邮件的完整信息和状态管理
    """
    __tablename__ = 'emails'
    
    id = db.Column(db.Integer, primary_key=True)
    sender_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False, index=True)
    recipient_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False, index=True)
    subject = db.Column(db.String(200), nullable=False)
    content = db.Column(db.Text, nullable=False)
    sent_at = db.Column(db.DateTime, default=datetime.utcnow, nullable=False, index=True)
    is_read = db.Column(db.Boolean, default=False, nullable=False)
    read_at = db.Column(db.DateTime)
    is_deleted_by_sender = db.Column(db.Boolean, default=False, nullable=False)
    is_deleted_by_recipient = db.Column(db.Boolean, default=False, nullable=False)
    
    def __init__(self, sender_id, recipient_id, subject, content):
        """
        初始化邮件对象
        
        Args:
            sender_id: 发送者ID
            recipient_id: 接收者ID
            subject: 邮件主题
            content: 邮件内容
        """
        self.sender_id = sender_id
        self.recipient_id = recipient_id
        self.subject = subject
        self.content = content
    
    def mark_as_read(self):
        """
        标记邮件为已读
        """
        if not self.is_read:
            self.is_read = True
            self.read_at = datetime.utcnow()
            db.session.commit()
    
    def delete_by_sender(self):
        """
        发送者删除邮件
        """
        self.is_deleted_by_sender = True
        db.session.commit()
    
    def delete_by_recipient(self):
        """
        接收者删除邮件
        """
        self.is_deleted_by_recipient = True
        db.session.commit()
    
    def is_deleted(self):
        """
        检查邮件是否被双方都删除
        
        Returns:
            bool: 是否被完全删除
        """
        return self.is_deleted_by_sender and self.is_deleted_by_recipient
    
    def get_sender_name(self):
        """
        获取发送者用户名
        
        Returns:
            str: 发送者用户名
        """
        return self.sender.username if self.sender else 'Unknown'
    
    def get_recipient_name(self):
        """
        获取接收者用户名
        
        Returns:
            str: 接收者用户名
        """
        return self.recipient.username if self.recipient else 'Unknown'
    
    def to_dict(self, user_id=None):
        """
        将邮件对象转换为字典
        
        Args:
            user_id: 当前用户ID，用于判断删除状态
        
        Returns:
            dict: 邮件信息字典
        """
        return {
            'id': self.id,
            'sender_id': self.sender_id,
            'sender_name': self.get_sender_name(),
            'recipient_id': self.recipient_id,
            'recipient_name': self.get_recipient_name(),
            'subject': self.subject,
            'content': self.content,
            'sent_at': self.sent_at.isoformat() if self.sent_at else None,
            'is_read': self.is_read,
            'read_at': self.read_at.isoformat() if self.read_at else None,
            'is_deleted_by_sender': self.is_deleted_by_sender,
            'is_deleted_by_recipient': self.is_deleted_by_recipient,
            'can_delete': user_id in [self.sender_id, self.recipient_id] if user_id else False
        }
    
    def __repr__(self):
        return f'<Email {self.id}: {self.subject[:30]}...>'

# 数据库初始化函数
def init_db():
    """
    初始化数据库
    创建所有表格
    """
    db.create_all()
    print("数据库表格创建完成")

def create_sample_data():
    """
    创建示例数据
    用于测试和演示
    """
    from config import Config
    
    # 获取邮箱域名配置
    email_domain = Config.EMAIL_DOMAIN
    
    # 创建示例用户
    if not User.query.filter_by(username='student1').first():
        student1 = User(username='student1', email=f'student1@{email_domain}', role='student')
        student1.set_password('123456')
        db.session.add(student1)
    
    if not User.query.filter_by(username='student2').first():
        student2 = User(username='student2', email=f'student2@{email_domain}', role='student')
        student2.set_password('123456')
        db.session.add(student2)
    
    db.session.commit()
    
    # 创建示例邮件
    student1 = User.query.filter_by(username='student1').first()
    student2 = User.query.filter_by(username='student2').first()
    
    if student1 and student2:
        if not Email.query.filter_by(sender_id=student1.id, recipient_id=student2.id).first():
            email1 = Email(
                sender_id=student1.id,
                recipient_id=student2.id,
                subject='欢迎使用邮箱系统',
                content='这是一封测试邮件，欢迎使用我们的邮箱系统！'
            )
            db.session.add(email1)
        
        if not Email.query.filter_by(sender_id=student2.id, recipient_id=student1.id).first():
            email2 = Email(
                sender_id=student2.id,
                recipient_id=student1.id,
                subject='回复：欢迎使用邮箱系统',
                content='谢谢你的邮件！这个系统很好用。'
            )
            db.session.add(email2)
    
    db.session.commit()
    print("示例数据创建完成")